/**
 * File: server.js
 * Project: newreact
 * Created Date: Tuesday 2018/01/02 14:15:44
 * Author: zhengjiang
 * -----
 * Last Modified: Tuesday 2018/01/02 14:18:51
 * Modified By: zhengjiang
 * -----
 * Description: 
 * 
 */


const express = require('express');
const next = require('next');
const LRUCache = require('lru-cache');
const { parse } = require('url');
const { join, extname } = require('path');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev, dir: './dist' });
const handle = app.getRequestHandler();

// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
	max: 100,
	maxAge: 1000 // * 60 * 60 // 1hour
});

app.prepare().then(() => {
	const server = express();

	server.use('/static', express.static('dist/static'));

	server.get('/index', (req, res) => {
		return renderAndCache(req, res, '/index', req.query);
	});

	server.get('*', (req, res) => {
		const parsedUrl = parse(req.url, true);

		handle(req, res, parsedUrl);
	});

	server.listen(port, (err) => {
		if (err) throw err;
		console.log(`> Ready on http://localhost:${port}`);
	});
});

function getCacheKey(req) {
	return `${req.url}`;
}

function renderAndCache(req, res, pagePath, queryParams) {
	const key = getCacheKey(req);
	// If we have a page in the cache, let's serve it
	if (ssrCache.has(key)) {
		res.send(ssrCache.get(key));
		return;
	}

	// If not let's render the page into HTML
	app
		.renderToHTML(req, res, pagePath, queryParams)
		.then((html) => {
			// Let's cache this page
			ssrCache.set(key, html);

			res.send(html);
		})
		.catch((err) => {
			app.renderError(err, req, res, pagePath, queryParams);
		});
}